#include "articlemodel.h"
#include "newspaper/newspapermanager.h"
#include "newspaper/article.h"
#include "newspaper/categorydetail.h"
#include <QDebug>
#include <QDateTime>


ArticleListModel::ArticleListModel(QObject *parent)
    : QAbstractListModel(parent),m_articleItems()
{

}

void ArticleListModel::addArticleItem(Article* articleItem)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_articleItems.push_back(articleItem);
    endInsertRows();
}

void ArticleListModel::insertArticleItem(Article* articleItem, const int pos)
{
    beginInsertRows(QModelIndex(), pos, pos);
    m_articleItems.insert(pos,articleItem);
    endInsertRows();
}


int ArticleListModel::rowCount(const QModelIndex & parent) const {
    Q_UNUSED(parent);
    return m_articleItems.count();
}

QVariant ArticleListModel::data(const QModelIndex & index, int role) const {
    if (index.row() < 0 || index.row() >= m_articleItems.count())
        return QVariant();

    const Article* articleitem = m_articleItems[index.row()];

    if (role == IdRole)
        return QVariant::fromValue<qulonglong>(articleitem->getId());
    else if (role == ThumbnailImageRole)
        return articleitem->linkSmallThumbnail();
    else if (role == TitleRole)
        return articleitem->title();
    else if( role == PostTimeRole)
    {
        QDateTime dateTime;
        dateTime.setMSecsSinceEpoch(articleitem->posttime());
        int subTime =  qAbs(QDateTime::currentDateTime().time().secsTo(dateTime.time()));

        QString time;
        if ( subTime / 3600 > 0) {
            time = QVariant(subTime / 3600).toString() + " giờ trước";
        } else {
            time = QVariant(subTime / 60).toString() + "  phút trước";
        }
        return time;
    }
    else if( role == SourceArticleRole)
    {
        SourceInfo sourceInfo = NewspaperManager::instance()->getSourceInfo(articleitem->sid());
        return sourceInfo.name();
    }
    return QVariant();
}


QHash<int, QByteArray> ArticleListModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[IdRole] = "articleId";
    roles[ThumbnailImageRole] = "thumbnailImage";
    roles[TitleRole] = "title";
    roles[PostTimeRole] = "postTime";
    roles[SourceArticleRole] = "sourceArticle";
    return roles;
}

void ArticleListModel::setListArticle(const QList<Article*> &articleItems)
{
    beginResetModel();
    m_articleItems = articleItems;
    endResetModel();
}

void ArticleListModel::clear()
{
    beginResetModel();
    m_articleItems.clear();
    endResetModel();
}

